package com.nuoniu.sibanyun.controller.crm;

import com.alibaba.fastjson.JSONObject;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.ueditor.ActionEnter;
import com.nuoniu.sibanyun.config.YmlConfig;
import com.nuoniu.sibanyun.entity.SysFile;
import com.nuoniu.sibanyun.service.ISysFileService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import com.nuoniu.sibanyun.utils.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 上传文件
 * @author 小啊刚
 * @date 2020/6/27
 */
@RestController
@CrossOrigin
@Api(value="上传文件 ",tags={"上传文件"})
public class UploadFileController {

    @Autowired
    private ISysFileService fileService;

    /**
     * 文件上传
     * @author 小啊刚
     * @date 2020/6/27
     */
    @PostMapping("uploadFile")
    @ApiOperation(value = "文件上传",tags = "APP_上传文件")
    public SysFile uploadFiles(MultipartFile[] file) {
        if(file == null || file.length == 0) {
            throw new NuoNiuException("文件不能为空");
        }

        UserInfo userInfo = UserThreadLocal.get();
        SysFile sysFile = new SysFile();
        List<String> fileUrl = FileUtils.uploadFile(file, 1,null);
        if(fileUrl.size() > 0) {
            sysFile.setName(file[0].getOriginalFilename());
            sysFile.setType(FileUtils.getFileExtName(file[0].getOriginalFilename()));
            sysFile.setStatus("done");
            sysFile.setCreateUserId(userInfo.getUserId());
            sysFile.setCreateUserName(userInfo.getRealName());
            sysFile.setUrl(YmlConfig.DOWNLOAD_FILE_URL + fileUrl.get(0));
            sysFile.setThumbUrl(YmlConfig.DOWNLOAD_FILE_URL + fileUrl.get(0));
            fileService.save(sysFile);
        }
        return sysFile;
    }

    /**
     * 富文本上传文件
     * @param request
     * @param response
     * @param action
     */
    @RequestMapping(value="/editorUpload")
    @CrossOrigin
    public void editorUpload(HttpServletRequest request, HttpServletResponse response, String action, MultipartFile[] upfile) {
        //String rootPath = "F:/project/project/sibanyun-parent/framework/src/main/resources/";
        String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();

        try {
            if("config".equals(action)){    //如果是初始化
                String exec = new ActionEnter(request, rootPath).exec();
                response.setCharacterEncoding( "utf-8" );
                response.setHeader("Content-Type" , "text/html");
                response.getWriter().write(exec);
                response.getWriter().flush();
                response.getWriter().close();
            }else if("uploadimage".equals(action) || "uploadvideo".equals(action) || "uploadfile".equals(action)){    //如果是上传图片、视频、和其他文件
                try {
                    for(MultipartFile file: upfile){
                        JSONObject jo = new JSONObject();
                        long size = file.getSize();    //文件大小
                        String originalFilename = file.getOriginalFilename();  //原来的文件名
                        String uploadInfo = FileUtils.upload(file);
                        if(!"".equals(uploadInfo)){ //如果上传成功
                            jo.put("state", "SUCCESS");
                            jo.put("original", originalFilename);//原来的文件名
                            jo.put("size", size);//文件大小
                            jo.put("title", originalFilename);//随意，代表的是鼠标经过图片时显示的文字
                            jo.put("type", FilenameUtils.getExtension(originalFilename)); //文件后缀名
                            jo.put("url", YmlConfig.DOWNLOAD_FILE_URL + uploadInfo);//这里的url字段表示的是上传后的图片在图片服务器的完整地址（http://ip:端口/***/***/***.jpg）
                        }else{    //如果上传失败
                        }

                        response.setCharacterEncoding( "utf-8" );
                        response.setHeader("X-Frame-Options", "SAMEORIGIN");
                        response.setHeader("Content-Type" , "text/html");
                        response.getWriter().write(jo.toString());
                        response.getWriter().flush();
                        response.getWriter().close();
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
        }
        //return null;
    }
}
